package cn.wolfcode.crm.service.imp;


import cn.wolfcode.crm.domain.Charge;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.MemberInfo;
import cn.wolfcode.crm.mapper.ChargeMapper;
import cn.wolfcode.crm.mapper.MemberInfoMapper;
import cn.wolfcode.crm.qo.PageResult;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.IChargeService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class ChargeServiceImpl implements IChargeService {
    @Autowired
    private ChargeMapper chargeMapper;
    @Autowired
    private MemberInfoMapper memberInfoMapper;


    @Override

    public void save(Charge record, Long memberId) {
        if (record != null) {
            //旧的余额 通过会员信息查询会员余额
            MemberInfo vip = memberInfoMapper.selectByPrimaryKey(memberId);
            BigDecimal oldBalance = vip.getBalance();

            record.setOldBalance(oldBalance);
            //设置卡号
            record.setCardNumber(vip.getCardnumber());
            //充值金额 前台传入
            BigDecimal chargeAmount = record.getChargeAmount();
            //充值后的余额
            BigDecimal newBalance = chargeAmount.add(oldBalance);
            record.setNewBalance(newBalance);
            //更新会员信息中的余额,和总充值金额
            BigDecimal chargerTotalAmount = vip.getChargeTotalAmount().add(record.getChargeAmount());
            memberInfoMapper.updateBalance(newBalance,memberId,chargerTotalAmount);
            //充值时间
            record.setChargeDate(new Date());
            //操作人
            Employee user = (Employee) SecurityUtils.getSubject().getPrincipal();
            record.setUserId(user.getId());
            record.setUsername(user.getUsername());
            chargeMapper.insert(record);
        }

    }

  

    @Override
    public List<Charge> selectAll() {
        List<Charge> depts = chargeMapper.selectAll();
        return depts;
    }


    @Override
    public List<Charge> queryByCard(String cardNumber) {

        return chargeMapper.queryByCardNumber(cardNumber);
    }

    @Override
    public PageResult queryForList(QueryObject qo) {
        int rows = chargeMapper.rows(qo);
        if (rows==0) {
            return PageResult.EMPTY_RESULT;
        }
        PageResult result =  new PageResult(rows,chargeMapper.queryForList(qo));
        return result;
    }


}
